<?php
/*********************************************************************************
 * Copyright (C) 2011-2013 X2Engine Inc. All Rights Reserved.
 *
 * X2Engine Inc.
 * P.O. Box 66752
 * Scotts Valley, California 95067 USA
 *
 * Company website: http://www.x2engine.com
 * Community and support website: http://www.x2community.com
 *
 * X2Engine Inc. grants you a perpetual, non-exclusive, non-transferable license
 * to install and use this Software for your internal business purposes.
 * You shall not modify, distribute, license or sublicense the Software.
 * Title, ownership, and all intellectual property rights in the Software belong
 * exclusively to X2Engine.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.
 ********************************************************************************/

/* @edition:pro */

/**
 * @package X2CRM.modules.marketing.controllers
 */
class WeblistController extends x2base {
	public $modelClass = 'X2List';

	public function accessRules() {
		return array(
			array('allow',
				'actions'=>array('index','view','create','update','delete'),
				'users'=>array('@'),
			),
		);
	}

	public function actionCreate() {
		if (isset($_POST['X2List'])) {
			$list = new X2List;
			$list->setAttributes($_POST['X2List']);
			$list->modelName = 'Contacts';
			$list->type = 'weblist';
			$list->createDate = time();
			$list->lastUpdated = time();

			//special case: "Default Newsletter" is system created only
			if ($list->name == "Default Newsletter") {
				if (Yii::app()->request->isAjaxRequest) {
					echo json_encode(array('errors'=>array('name'=>Yii::t('marketing','Name cannot be') .' "Default Newsletter"')));
				} else {
					Yii::app()->user->setFlash('error', Yii::t('marketing','Name cannot be') .' "Default Newsletter"');
					$this->redirect(array('index'));
				}
			}

			if ($list->save()) {
				if (!Yii::app()->request->isAjaxRequest)
					$this->redirect(array('index'));
			} else {
				if (Yii::app()->request->isAjaxRequest) {
					echo json_encode(array('errors'=>$list->getErrors()));
				} else {
					Yii::app()->user->setFlash('error', Yii::t('marketing','Name cannot be blank.'));
					$this->redirect(array('index'));
				}
			}
		} else {
			$this->redirect(array('index'));
		}
	}

	public function actionView($id) {
		$list = X2List::load($id);

		if (!isset($list)) {
			Yii::app()->user->setFlash('error', Yii::t('app', 'The requested page does not exist.'));
			$this->redirect(array('lists'));
		}

		if ($list->type != 'weblist') {
			$this->redirect(array('/contacts/list,','id'=>$list->id));
		}

		$this->render('view', array('model'=>$list));
	}

	public function actionUpdate($id) {
		$model = X2List::load($id);

		if (!isset($model)) {
			Yii::app()->user->setFlash('error', Yii::t('app', 'The requested page does not exist.'));
			$this->redirect(array('index'));
		}

		if (isset($_POST['X2List'])) {
			$model->attributes = $_POST['X2List'];
			$model->lastUpdated = time();
			$model->save();
			$this->redirect(array('view', 'id'=>$id));
		}

		$this->render('update', array('model'=>$model));
	}

	public function actionDelete($id) {
		if(Yii::app()->request->isPostRequest) {
			$model = X2List::load($id);

			if (!isset($model)) {
				Yii::app()->user->setFlash('error', Yii::t('app', 'The requested page does not exist.'));
				$this->redirect(array('index'));
			}

			$this->cleanUpTags($model);
			$model->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax'])) {
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
			}
		} else {
			Yii::app()->user->setFlash('error', Yii::t('app', 'Invalid request. Please do not repeat this request again.'));
			$this->redirect(array('index'));
		}
	}

	public function actionIndex() {
		if(Yii::app()->user->getName()!='admin') {
		$condition = ' AND visibility="1" OR assignedTo="Anyone"  OR assignedTo="'.Yii::app()->user->getName().'"';
			/* x2temp */
			$groupLinks = Yii::app()->db->createCommand()->select('groupId')->from('x2_group_to_user')->where('userId='.Yii::app()->user->getId())->queryColumn();
			if(!empty($groupLinks))
				$condition .= ' OR assignedTo IN ('.implode(',',$groupLinks).')';

			$condition .= ' OR (visibility=2 AND assignedTo IN
				(SELECT username FROM x2_group_to_user WHERE groupId IN
				(SELECT groupId FROM x2_group_to_user WHERE userId='.Yii::app()->user->getId().')))';
		} else {
			$condition='';
		}
		$dataProvider = new SmartDataProvider('X2List', array(
			'criteria'=>array('condition'=>'type="weblist"'.$condition),
			'sort'=>array('defaultOrder'=>'createDate DESC'),
		));
		$this->render('index', array('dataProvider'=>$dataProvider));
	}

	public function actionWeblist() {
		/* This action is largely the same as the /contacts/weblead, with some differences:
		 * - It creates a list item with an email address rather than a contact, though it may
         *      reference an existing contact
		 * - Each entry is always associated with a list, using a default when no other specified
		 * - The web list form only takes email address as input
		 */
		if (Yii::app()->request->isPostRequest) {
			$now = time();
			$list = null;

			//look up list by id
			if (!empty($_GET['lid']) && ctype_digit((string)$_GET['lid'])) {
				$listId = $_GET['lid'];
				$list = X2List::model()->findByPk($listId, 'type="weblist"');
			}

			//look for "Default Newsletter"
			if (!isset($list)) {
				$list = X2List::model()->findByAttributes(
                    array('name'=>'Default Newsletter'), 'type="weblist"');
			}

			//create it otherwise
			if (!isset($list)) {
				$list = new X2List;
				$list->name = 'Default Newsletter';
				$list->description = Yii::t('contacts','Default list for email list signups');
				$list->type = 'weblist';
				$list->modelName = 'Contacts';
				$list->visibility = 1;
				$list->assignedTo = 'admin';
				$list->createDate = $now;
				$list->lastUpdated = $now;
				if (!$list->save()) $list = null;
			}

			//we just can't get a list, very unlikely
			if (!isset($list)) {
				$this->renderPartial('application.modules.contacts.views.contacts.webleadSubmit',
					array('error'=>Yii::t('contacts','This request cannot be made at this time.')));
				return;
			}

			//require email field, check format
			$email = $_POST['Contacts']['email'];
			if (preg_match("/[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/", $email) == 0) {
				$this->renderPartial('application.modules.contacts.views.contacts.webleadSubmit',
					array('error'=>Yii::t('contacts','Invalid Email Address')));
				return;
			}

			//see if that email has already signed up
			$listItem = X2ListItem::model()->findByAttributes(
                array('emailAddress'=>$email, 'listId'=>$list->id));

			if (!isset($listItem)) {
				$listItem = new X2ListItem;
				$listItem->listId = $list->id;
				$listItem->emailAddress = $email;
				$list->count++;
			}

			//use the submitted info to create an action
			$action = new Actions;
			$action->actionDescription = Yii::t('contacts','Newsletter Signup') .": ". $email;
			$action->associationType = 'X2List';
			$action->associationId = $list->id;
			$action->associationName = $list->name;
			$action->type = 'note';
			$action->assignedTo = $list->assignedTo;
			$action->visibility = $list->visibility;
			$action->createDate = $now;
			$action->lastUpdated = $now;
			$action->completeDate = $now;
			$action->complete = 'Yes';
			$action->updatedBy = 'admin';

			//check for existing contact with email address
			$contact = Contacts::model()->findByAttributes(array('email'=>$email));

			if (isset($contact)) {
				//add contact to the list
				$listItem->contactId = $contact->id;
				//create second action for contact record
				$contactAction = new Actions;
				$contactAction->setAttributes($action->getAttributes());
				$contactAction->actionDescription = Yii::t('contacts','Newsletter Signup') .": ".
                    $list->name;
				$contactAction->associationType = 'contacts';
				$contactAction->associationId = $contact->id;
				$contactAction->associationName = $contact->firstName ." ". $contact->lastName;
				$contactAction->assignedTo = $contact->assignedTo;
				$contactAction->visibility = $contact->visibility;
			}

			$transaction = Yii::app()->db->beginTransaction();
			try {
				if (!$listItem->save())
                    throw new Exception(array_shift(array_shift($listItem->getErrors())).'listiem');
				if (!$list->save())
                    throw new Exception(array_shift(array_shift($list->getErrors())));
				$action->save();
				if (isset($contactAction)) $contactAction->save();

				$transaction->commit();
				$this->renderPartial('application.components.views.webFormSubmit',
                    array ('type'=>'weblist'));
			} catch (Exception $e) {
				$transaction->rollBack();
				Yii::app()->user->setFlash(
                    'error', Yii::t('contacts','Could not sign up') .': '. $e->getMessage());
				$this->redirect($this->createUrl('', array('lid'=>$list->id)));
			}
		} else {
            WebFormAction::sanitizeGetParams ();

			$this->renderPartial('application.components.views.webForm', array('type'=>'weblist'));
		}
	}
}
